import 'dart:io';
import 'oauth_interceptor.dart';
import 'extra_keys.dart';
import 'toast_interceptor.dart';
import 'package:dio/dio.dart';
import 'error_interceptor.dart';

class HttpClient {
  static final HttpClient client = HttpClient._init();

  /// 请求超时时间
  final int _connectTimeout = 60000;

  /// 响应超时时间
  final int _receiveTimeout = 60000;

  /// api请求地址
  final String _baseUrl = "http://192.168.10.113:8180";

  // /// 是否开启调试
  // final bool _isDebug = false;

  /// 是否打印请求日志
  final bool _isLogsEnabled = false;

  // static const String x_www_form_urlencoded =
  //     'application/x-www-form-urlencoded';
  // static final ContentType form = ContentType.parse(x_www_form_urlencoded);
  /// 请求的Content-Type，默认值是"application/json; charset=utf-8".
  /// 如果您想以"application/x-www-form-urlencoded"格式编码请求数据,
  /// 统一全部默认为,不作更改 `Headers.formUrlEncodedContentType`
  final String form = Headers.formUrlEncodedContentType;

  late Dio _dio;
  late Dio _tokenDio;

  HttpClient._init() {
    BaseOptions options = BaseOptions(
      baseUrl: _baseUrl,
      connectTimeout: _connectTimeout,
      receiveTimeout: _receiveTimeout,
      contentType: Headers.formUrlEncodedContentType,
      // responseType: ResponseType.json,
      headers: {
        HttpHeaders.userAgentHeader: "dio",
        "api-version": "1.0.0",
        "plateform": Platform.operatingSystem,
      },
      validateStatus: (status) => status! >= 200 && status < 400,
      extra: {
        ExtraKeys.needErrorToast: true,
        ExtraKeys.needToast: false,
        ExtraKeys.needToken: true,
        ExtraKeys.needLoading: false,
      },
    );
    _dio = Dio(options);
    _tokenDio = Dio(options);

    // flutter使用dio请求时(默认抓取不了)
    // 使用Charles对Flutter应用程序抓包
    // _dio.httpClientAdapter = DefaultHttpClientAdapter();
    // (_dio.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate =
    //     (client) {
    //   client.findProxy = (uri) {
    //     //proxy all request to localhost:8888
    //     return "PROXY 192.168.0.5:8888";
    //   };
    //   client.badCertificateCallback =
    //       (X509Certificate cert, String host, int port) => true;
    // };

    // oauth2 拦截器放在第1位
    OauthInterceptor oauthInterceptor = OauthInterceptor();
    _dio.interceptors.add(oauthInterceptor);

    // 添加错误处理拦截器放在第4位
    ErrorInterceptor errorInterceptor = ErrorInterceptor();
    _dio.interceptors.add(errorInterceptor);
    _tokenDio.interceptors.add(errorInterceptor);

    // 网络弹出提示拦截器放在第5位
    ToastInterceptor toastInterceptor = ToastInterceptor();
    _dio.interceptors.add(toastInterceptor);
    _tokenDio.interceptors.add(toastInterceptor);

    // 添加日志打印拦截器, 放在最后面
    if (_isLogsEnabled) {
      LogInterceptor logInterceptor = LogInterceptor(
        requestBody: true,
        responseBody: true,
      );
      _dio.interceptors.add(logInterceptor);
      _tokenDio.interceptors.add(logInterceptor);
    }
  }
}
